use log::LevelFilter;
use rbatis::dark_std::defer;
use rbatis::rbatis::RBatis;

/// make an RBatis
pub async fn init_db() -> RBatis {
    let rb = RBatis::new();
    // ------------choose database driver------------
    // rb.init(rbdc_mysql::driver::MysqlDriver {}, "mysql://root:123456@localhost:3306/test").unwrap();
    // rb.init(rbdc_pg::driver::PgDriver {}, "postgres://postgres:123456@localhost:5432/postgres").unwrap();
    // rb.init(rbdc_mssql::driver::MssqlDriver {}, "mssql://SA:TestPass!123456@localhost:1433/test").unwrap();
    rb.init(
        rbdc_sqlite::driver::SqliteDriver {},
        "sqlite://target/sqlite.db",
    )
        .unwrap();

    // ------------create tables/ init table data------------
    let sql_file = match rb.driver_type().unwrap() {
        "sqlite" => "table_sqlite.sql",
        "postgres" => "table_postgres.sql",
        "mysql" => "table_mysql.sql",
        "mssql" => "table_mssql.sql",
        _ => { "" }
    };
    if sql_file != "" {
        let sql = std::fs::read_to_string(sql_file).unwrap();
        let raw = fast_log::LOGGER.get_level().clone();
        fast_log::LOGGER.set_level(LevelFilter::Off);
        defer!(|| {
        fast_log::LOGGER.set_level(raw);
    });
        let _ = rb.exec(&sql, vec![]).await;
    }
    // ------------create tables/ init table data------------
    return rb;
}
